import type { FC } from 'react';
import React from 'react';

import BScroll from '@better-scroll/core';
import { useMount, useSize, useUpdateEffect } from 'ahooks';
import clsx from 'clsx';

import type { Options } from '@better-scroll/core';

// 添加详细的类型定义和方法级注释
interface Props extends React.ComponentProps<'div'> {
	/**
	 * BetterScroll options
	 *
	 * @link https://better-scroll.github.io/docs/zh-CN/guide/base-scroll-options.html
	 */
	options: Options;
	/**
	 * 设置 BetterScroll 实例
	 *
	 * @param bsScroll - BetterScroll 实例
	 */
	setBsScroll: (bsScroll: BScroll) => void;
}

/**
 * BetterScroll 组件
 *
 * @param {Props} props - 组件属性
 * @returns {JSX.Element} - 渲染的组件
 */
const BetterScroll: FC<Props> = memo(({ children, className, options, setBsScroll, ...rest }) => {
	const bsWrapper = useRef<HTMLDivElement>(null);
	const bsContent = useRef<HTMLDivElement>(null);
	const bsWrapperSize = useSize(bsWrapper);
	const bsContentSize = useSize(bsContent);
	const instance = useRef<BScroll | null>(null);

	const isScrollY = Boolean(options.scrollY);

	/**
	 * 初始化 BetterScroll 实例
	 */
	function initBetterScroll() {
		if (!bsWrapper.current) return;
		instance.current = new BScroll(bsWrapper.current, options);

		setBsScroll(instance.current);
	}

	useUpdateEffect(() => {
		instance.current?.refresh();
	}, [bsWrapperSize?.width, bsContentSize?.width]);

	useMount(() => {
		initBetterScroll();
	});

	return (
		<div ref={bsWrapper} {...rest} className={clsx('h-full text-left', className)}>
			<div className={clsx('inline-block', { 'h-full': !isScrollY })} ref={bsContent}>
				{children}
			</div>
		</div>
	);
});

// 典型用法示例
// import BetterScroll from './BetterScroll';
//
// function App() {
//   const handleSetBsScroll = (bsScroll) => {
//     console.log('BetterScroll instance:', bsScroll);
//   };
//
//   return (
//     <BetterScroll options={{ scrollY: true }} setBsScroll={handleSetBsScroll}>
//       <div>Content goes here</div>
//     </BetterScroll>
//   );
// }
//
// export default App;
export default BetterScroll;
